
/*
 * @Author: 谢陈洁
 * @Date: 2025-07-14 11:20:07
 * @LastEditors: 谢陈洁
 * @LastEditTime: 2025-07-18 15:57:23
 * @Description: useTableData 表格数据 hooks 封装
 * @Params: T 泛型 表格数据类型 fetchApi 表格数据接口 params 参数
 * @Return: { dataList, loading, pagination, fetchData, handlePaginationChange }
*/
export function useTableData<T>(

  fetchApi: (params: any) => Promise<{ list: T[]; total?: number }>,
  options:{
    hasPagination?: boolean, // 是否有分页
  }= {
    hasPagination: true, // 是否有分页
  }) {
  const dataList: Ref<T[]> = ref([]) // 表格数据
  const searchParams = ref<Record<string, any>>({}) // 搜索参数
  const loading = ref(false) // 加载中
  const pagination = reactive({
    pageSize: 10,
    pageIndex: 1,
    total: 0,
  })
  const fetchData = async (params?: Record<string, any>) => {
    loading.value = true
    if(params){
      pagination.pageIndex = 1
      searchParams.value = params
    }
    const requestParams = { ...searchParams.value }
    if (options.hasPagination) {
      Object.assign(requestParams, {
        pageSize: pagination.pageSize,
        pageIndex: pagination.pageIndex,
      })
    }
      try {
        const res = await fetchApi(requestParams)
        dataList.value = res?.list || res || []
        if (options.hasPagination && res?.total) {
          pagination.total = res.total
        }
      } finally {
        loading.value = false
      }
  }
  const handlePaginationChange = (params: { pageIndex: number; pageSize: number }) => {
    if (!options.hasPagination) return
    pagination.pageIndex = params.pageIndex
    pagination.pageSize = params.pageSize
    fetchData() // 自动携带之前的搜索参数
  }

  return {
    dataList,
    loading,
    pagination,
    fetchData,
    handlePaginationChange
  }
}
